{% extends "base.html" %}

{% block styles %}
<link rel="stylesheet" href="{{ url_for('static', filename='game_translate.css') }}">
{% endblock %}

{% block scripts %}
<script>
    let currentWordIndex = 0;
    let words = {{ words|tojson }};
    let score = 0;
    let completedWords = 0;
    let completionRate = 0;
    let wordResults = {};
    let isChecking = false;

    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('translation').focus();
        const firstWordAudio = words[0].audio;
        playAudioTwice(firstWordAudio);
    });

    function playAudioTwice(audioUrl) {
        const audio = new Audio(audioUrl);
        let playCount = 0;
        
        audio.addEventListener('ended', function() {
            playCount++;
            if (playCount < 2) {
                audio.play();
            }
        });
        
        audio.play();
    }

    function playAudio(audioUrl) {
        console.log(audioUrl);
        playAudioTwice(audioUrl);
    }

    function showFeedback(isCorrect, message) {
        const feedback = document.getElementById('feedback');
        feedback.style.display = 'block';
        feedback.className = 'feedback ' + (isCorrect ? 'correct' : 'incorrect');
        feedback.textContent = message;
    }

    async function checkAnswer() {
        if (isChecking) return;

        const translationInput = document.getElementById('translation');
        const skipButton = document.querySelector('.skip-btn');
        const loadingDots = document.getElementById('loading-dots');
        const userAnswer = translationInput.value.trim();
        
        if (!userAnswer) {
            translationInput.focus();
            translationInput.classList.add('shake');
            setTimeout(() => {
                translationInput.classList.remove('shake');
            }, 820);
            return;
        }

        isChecking = true;
        translationInput.disabled = true;
        skipButton.disabled = true;
        loadingDots.style.display = 'block';

        const currentWord = words[currentWordIndex];
        
        const response = await fetch('/check_translation', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                user_answer: userAnswer,
                english_word: currentWord.english
            })
        });
        
        const result = await response.json();
        
        loadingDots.style.display = 'none';
        isChecking = false;

        showFeedback(result.correct, result.message);
        if (result.correct) {
            score++;
            completedWords++;
            completionRate = (completedWords / words.length).toFixed(2);
            document.getElementById('score').textContent = 
                `Score: ${score} | Completion Rate: ${(completionRate * 100).toFixed(1)}%`;
            wordResults[currentWord.english] = {
                word: currentWord.english,
                correct: true
            };
            setTimeout(() => {
                translationInput.disabled = false;
                skipButton.disabled = false;
                nextWord();
            }, 3000);
        } else {
            wordResults[currentWord.english] = {
                word: currentWord.english,
                correct: false
            };
            setTimeout(() => {
                translationInput.disabled = false;
                skipButton.disabled = false;
                nextWord();
            }, 4000);
        }
    }

    function endGame() { 
        const gameContainer = document.querySelector('.game-container');
        gameContainer.classList.add('disabled');
        gameContainer.style.pointerEvents = 'none';

        document.getElementById('remaining-words').textContent = '0';

        const translationInput = document.getElementById('translation');
        translationInput.disabled = true;

        const wordResultsArray = Object.values(wordResults);

        fetch('/submit_game_result', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                game_id: '{{ game_id }}',
                game_mode: 'translate',
                score: score,
                completion_rate: completionRate,
                word_results: wordResultsArray
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Game result submitted:', data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });

        showWordList();
    }

    function showWordList() {
        const wordlistContainer = document.getElementById('wordlist-container');
        const wordResultsList = document.getElementById('word-results');
        
        wordlistContainer.style.display = 'block';
        wordResultsList.innerHTML = '';

        words.forEach(word => {
            const listItem = document.createElement('li');
            const wordSpan = document.createElement('span');
            const iconSpan = document.createElement('span');
            
            wordSpan.textContent = word.english;
            
            iconSpan.className = 'word-result-icon';
            if (wordResults[word.english] && wordResults[word.english].correct) {
                iconSpan.className += ' correct';
                iconSpan.innerHTML = '&#10004;'; // Checkmark
            } else {
                iconSpan.className += ' incorrect';
                iconSpan.innerHTML = '&#10008;'; // Cross
            }
            
            listItem.appendChild(wordSpan);
            listItem.appendChild(iconSpan);
            wordResultsList.appendChild(listItem);
        });
    }

    function nextWord() {
        currentWordIndex++;
        if (currentWordIndex >= words.length) {
            endGame();
            return;
        }
        
        const word = words[currentWordIndex];
        
        document.getElementById('remaining-words').textContent = words.length - currentWordIndex;
        
        document.querySelector('.english-word').textContent = word.english;
        
        // Update phonetic text while preserving the audio icon
        const phoneticDiv = document.querySelector('.word-phonetic');
        phoneticDiv.childNodes[0].textContent = `(${word.phonetic})`; // Update text node
        const audioIcon = phoneticDiv.querySelector('.audio-icon');
        audioIcon.setAttribute('onclick', `playAudio('${word.audio}')`);
        
        document.querySelector('.word-example').textContent = word.example;
        
        const translationInput = document.getElementById('translation');
        translationInput.value = '';
        translationInput.focus();
        
        document.getElementById('feedback').style.display = 'none';
        
        playAudioTwice(word.audio);
    }

    function skipWord() {
        if (isChecking) return;
        
        const currentWord = words[currentWordIndex];
        wordResults[currentWord.english] = {
            word: currentWord.english,
            correct: false
        };
        
        nextWord();
    }
</script>
{% endblock %}

{% block content %}
<div id="score">Score: 0</div>
<div class="game-area">
    <div class="game-header">
        <h1>{{ game_title }}</h1>
        <div class="word-count">Remaining Words: <span id="remaining-words">{{ words|length }}</span></div>
    </div>
    <div class="game-container">
        <div class="word-section">
            <div class="english-word" id="english-word">{{ words[0].english }}</div>
            <div class="word-phonetic">
                ({{ words[0].phonetic }})
                <span class="audio-icon" onclick="playAudio('{{ words[0].audio }}')">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" class="speaker"></polygon>
                        <path d="M15.54 8.46a5 5 0 0 1 0 7.07" class="wave1"></path>
                        <path d="M19.07 4.93a10 10 0 0 1 0 14.14" class="wave2"></path>
                    </svg>
                </span>
            </div>
            <div class="word-example">{{ words[0].example }}</div>
        </div>

        <div class="input-section">
            <input type="text" 
                   id="translation" 
                   class="translation-input" 
                   placeholder="请输入中文翻译..."
                   autocomplete="off"
                   onkeydown="if(event.key === 'Enter') checkAnswer()">
            <div id="loading-dots" style="display: none; text-align: center; margin-top: 10px;">
                <span class="dot">.</span>
                <span class="dot">.</span>
                <span class="dot">.</span>
            </div>
            <div class="button-group">
                <button class="game-button confirm-btn" onclick="checkAnswer()">OK</button>
                <button class="game-button skip-btn" onclick="skipWord()">SKIP</button>
            </div>
            <div id="feedback" class="feedback"></div>
        </div>
    </div>
</div>

<div id="wordlist-container" style="display: none;">
    <div class="wordlist-column">
        <ul id="word-results"></ul>
    </div>
</div>
{% endblock %}